package com.teaching.management.controller;

import com.teaching.management.entity.User;
import com.teaching.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpSession;

/**
 * @author Twelve
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
            @RequestParam String password,
            @RequestParam String role,
            Model model,
            HttpSession session) {
        // 验证用户信息
        User user = userService.authenticate(username, password, role);

        if (user != null) {
            // 登录成功，将用户信息存入session
            session.setAttribute("user", user);

            // 根据角色重定向到不同的页面
            return switch (role) {
                case "管理员" -> "/admin/dashboard";
                case "教师" -> "/teacher/dashboard";
                case "学生" -> "/student/dashboard";
                default -> {
                    model.addAttribute("error", "无效的角色");
                    yield "login";
                }
            };
        } else {
            // 登录失败
            model.addAttribute("error", "密码错误，请重新输入");
            // 保留用户名和角色
            model.addAttribute("username", username);
            model.addAttribute("selectedRole", role);
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "/login";
    }
}